# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

class Dvd(db.Model):
    name = db.StringProperty(required=True)
    owner = db.UserProperty()

    description = db.TextProperty()
    url = db.URLProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)

class DvdForm(djangoforms.ModelForm):
    class Meta:
        model = Dvd
        exclude = ['owner', 'created', 'modified']

def respond(request, user, template, params=None):
    """Helper to render a response, passing standard stuff to the response.

    Args:
      request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

    Returns:
      Whatever render_to_response(template, params) returns.

    Raises:
      Whatever render_to_response(template, params) raises.
    """
    if params is None:
        params = {}
    if user:
        params['user'] = user
        params['nickname'] = user.nickname()
        params['sign_out'] = users.CreateLogoutURL(request.path)
        params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
    else:
        params['sign_in'] = users.CreateLoginURL(request.path)
    if not template.endswith('.html'):
        template += '.html'
    return shortcuts.render_to_response(template, params)


def index(request):
    """Request / -- show all dvds."""
    user = users.GetCurrentUser()
    dvds = db.GqlQuery('SELECT * FROM Dvd ORDER BY created DESC')
    return respond(request, user, 'list', {'dvds': dvds})

def edit(request, dvd_id):
    """Create or edit a dvd.  GET shows a blank form, POST processes it."""
    user = users.GetCurrentUser()
    if user is None:
        return http.HttpResponseForbidden('You must be signed in to add or edit a dvd')

    dvd = None
    if dvd_id:
        dvd = Dvd.get(db.Key.from_path(Dvd.kind(), int(dvd_id)))
        if dvd is None:
            return http.HttpResponseNotFound('No dvd exists with that key (%r)' %dvd_id)

    form = DvdForm(data=request.POST or None, instance=dvd)

    if not request.POST:
        return respond(request, user, 'dvd', {'form': form, 'dvd': dvd})

    errors = form.errors
    if not errors:
        try:
            dvd = form.save(commit=False)
        except ValueError, err:
            errors['__all__'] = unicode(err)
    if errors:
        return respond(request, user, 'dvd', {'form': form, 'dvd': dvd})

    if not dvd.owner:
        dvd.owner = user
    dvd.put()

    return http.HttpResponseRedirect('/')

def new(request):
    """Create a dvd.  GET shows a blank form, POST processes it."""
    return edit(request, None)

def home(request):
    user = users.GetCurrentUser()
    if user is None:
        return user_request(request)
    if user:
        return respond(request, user, 'home.html', None)

def user_request(request):
    user = users.GetCurrentUser()
    if user:
        return http.HttpResponseRedirect('/home')
    else:
        return shortcuts.render_to_response('login.html', {'sign_in': users.CreateLoginURL(request.path)})
            
def myDvd(request):
    user = users.GetCurrentUser()
    if user is None:
        return user_request(request)
    if user:
        return respond(request, user, 'myDvdDummy.html', None)
